<template>
  <div class="knowledge-list">


    <div class="page-header">
      <h1>知识库管理</h1>
      <el-button type="primary" @click="openDialog('create')">新增知识库</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="知识库名称">
          <el-input v-model="searchForm.name" placeholder="请输入知识库名称" clearable @clear="handleSearch"
                    @keyup.enter.native="handleSearch"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 知识库列表 -->
    <el-table
        v-loading="loading"
        :data="paginatedKnowledge"
        border
        style="width: 100%">
      <el-table-column
          prop="id"
          label="ID"
          width="80">
      </el-table-column>
      <el-table-column
          prop="name"
          label="名称"
          width="180">
      </el-table-column>
      <el-table-column
          prop="content"
          label="内容">
        <template slot-scope="scope">
          <div class="content-preview">
            {{ scope.row.content }}
            <el-tag size="mini" type="success" v-if="scope.row.excalidraw" style="margin-left: 5px;">含画板</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          label="标签"
          width="200">
        <template slot-scope="scope">
          <el-tag
              v-for="tag in scope.row.tags"
              :key="tag.id"
              size="small"
              style="margin-right: 5px; margin-bottom: 5px;"
          >
            {{ tag.name }}
          </el-tag>
          <span v-if="!scope.row.tags || scope.row.tags.length === 0">无标签</span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          width="280">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="openDialog('view', scope.row)">查看
          </el-button>
          <el-button
              size="mini"
              type="primary"
              @click="openDialog('edit', scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="success"
              v-if="scope.row.excalidraw"
              @click="openExcalidrawDialog(scope.row)">画板
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button
              size="mini"
              type="info"
              @click="openAttachmentsDialog(scope.row)">附件
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredKnowledge.length">
      </el-pagination>
    </div>


  </div>
</template>

<script>
import ExcalidrawComponent from '@/components/ExcalidrawComponent.vue'
import {mapGetters} from 'vuex'
import {EventBus, EventNames} from '@/utils/eventBus'
import {Excalidraw} from '@excalidraw/excalidraw'
import {FormDialog} from "@/components/formDialog/index2";

export default {
  name: 'KnowledgeList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: ''
      },
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      // 对话框配置
      dialogVisible: false,
      dialogType: 'create', // create, edit, view
      // 当前操作的知识库
      currentKnowledge: {
        name: '',
        content: '',
        tags: []
      },
      // 表单验证规则
      rules: {
        name: [
          {required: true, message: '请输入知识库名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入知识库内容', trigger: 'blur'}
        ]
      },
      // 标签输入
      inputTagVisible: false,
      inputTagValue: '',

      // Excalidraw相关
      excalidrawInstance: null,
      excalidrawData: null,
      excalidrawDialogVisible: false,
      currentExcalidrawKnowledge: null,

      // 附件相关
      attachmentsDialogVisible: false,
      attachmentsLoading: false,
      attachmentsList: [],
      currentAttachmentKnowledgeId: null,


      resourceJson: null,
      darkMode: true,
      viewMode: false,
      gridMode: true,
      zenMode: false,
      excalidrawLoaded: false,
      jsonData: null
    }
  },
  computed: {
    ...mapGetters({
      knowledgeList: 'knowledge/getKnowledgeList',
      loading: 'knowledge/getLoading'
    }),

    // 对话框标题
    dialogTitle() {
      const titles = {
        create: '新增知识库',
        edit: '编辑知识库',
        view: '查看知识库'
      }
      return titles[this.dialogType] || '知识库'
    },

    // 过滤后的知识库列表
    filteredKnowledge() {
      if (!this.searchForm.name) {
        return this.knowledgeList
      }

      const keyword = this.searchForm.name.toLowerCase()
      return this.knowledgeList.filter(item => {
        return item.name.toLowerCase().includes(keyword)
      })
    },

    // 分页后的知识库列表
    paginatedKnowledge() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredKnowledge.slice(start, end)
    },

    // 是否显示Excalidraw编辑器
    showExcalidrawEditor() {
      // 编辑和创建模式始终显示编辑器
      // 查看模式下，只有当有excalidraw数据时才显示
      return this.dialogType !== 'view' ||
          (this.currentKnowledge && this.currentKnowledge.excalidraw)
    }
  },
  components: {
    ExcalidrawComponent
  },
  created() {
    // 获取知识库列表
    this.fetchKnowledgeList()

    // 监听事件总线上的事件
    EventBus.$on(EventNames.REFRESH_NOTES, this.fetchKnowledgeList)
  },
  beforeDestroy() {
    // 移除事件监听
    EventBus.$off(EventNames.REFRESH_NOTES, this.fetchKnowledgeList)
  },
  methods: {
    /**
     * 处理Excalidraw数据变更
     */
    handleExcalidrawChange(jsonData) {
      this.excalidrawData = jsonData
    },
    /**
     * 处理Excalidraw加载完成
     */
    handleExcalidrawLoaded() {
      this.excalidrawLoaded = true
      console.log('Excalidraw组件加载完成')
    },

    /**
     * 获取知识库列表
     */
    fetchKnowledgeList() {
      this.$store.dispatch('knowledge/fetchKnowledgeList')
    },

    /**
     * 格式化日期
     */
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    },

    /**
     * 处理搜索
     */
    handleSearch() {
      if (this.searchForm.name) {
        this.$store.dispatch('knowledge/searchKnowledge', this.searchForm.name)
      } else {
        this.fetchKnowledgeList()
      }
      this.pagination.currentPage = 1
    },

    /**
     * 重置搜索
     */
    resetSearch() {
      this.searchForm.name = ''
      this.fetchKnowledgeList()
      this.pagination.currentPage = 1
    },

    /**
     * 处理分页大小变化
     */
    handleSizeChange(val) {
      this.pagination.pageSize = val
    },

    /**
     * 处理当前页变化
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
    },

    /**
     * 打开对话框
     * @param {String} type - 对话框类型：create, edit, view
     * @param {Object} knowledge - 知识库对象（编辑和查看时需要）
     */
    async openDialog(type, knowledge = null) {
      await FormDialog({
        title: '管理文章',
        width: '888px',
        data() {
          return {id: knowledge?.id}
        },

        components: {
          modify: () => import('@/views/knowledgeList/modify.vue')
        }
      })
    },

    /**
     * 初始化Excalidraw编辑器
     */
    initExcalidraw() {


    },

    /**
     * 获取Excalidraw数据
     */
    getExcalidrawData() {
      if (!this.excalidrawInstance || !this.excalidrawData) return null
      return JSON.stringify(this.excalidrawData)
    },

    /**
     * 单独保存Excalidraw数据
     * 当用户只修改了画板而没有修改其他内容时使用
     */
    saveExcalidrawOnly() {
      if (!this.currentKnowledge.id) {
        this.$message.warning('请先保存知识库基本信息')
        return
      }

      const excalidrawData = this.getExcalidrawData()
      if (!excalidrawData) {
        this.$message.warning('画板数据为空，无需保存')
        return
      }

      this.$store.dispatch('knowledge/saveKnowledgeExcalidraw', {
        id: this.currentKnowledge.id,
        excalidraw: excalidrawData
      }).then(result => {
        if (result && result.success) {
          this.$message.success('画板数据保存成功')
        } else if (result && result.message) {
          this.$message.error(result.message)
        }
      })
    },

    /**
     * 加载Excalidraw数据
     * 当需要单独获取最新的Excalidraw数据时使用
     */
    loadExcalidrawData(id) {
      if (!id) return

      this.$store.dispatch('knowledge/getKnowledgeExcalidraw', id)
          .then(result => {
            if (result && result.success && result.data && result.data.excalidraw) {
              try {
                this.excalidrawData = JSON.parse(result.data.excalidraw)
                // 如果Excalidraw实例已经初始化，则更新场景
                if (this.excalidrawInstance) {
                  this.excalidrawInstance.updateScene(this.excalidrawData)
                }
              } catch (e) {
                console.error('解析Excalidraw数据失败:', e)
              }
            }
          })
    },

    /**
     * 处理表单提交
     */
    handleSubmit() {
      this.$refs.knowledgeForm.validate(valid => {
        if (!valid) return

        // 获取Excalidraw数据
        const excalidrawData = this.getExcalidrawData()
        if (excalidrawData) {
          this.currentKnowledge.excalidraw = excalidrawData
        }

        const action = this.dialogType === 'create' ? 'createKnowledge' : 'updateKnowledge'
        const successMsg = this.dialogType === 'create' ? '创建成功' : '更新成功'

        this.$store.dispatch(`knowledge/${action}`, this.currentKnowledge)
            .then(result => {
              if (result && result.success) {
                this.$message.success(successMsg)
                this.closeDialog() // 使用closeDialog方法关闭对话框并清理资源
              } else if (result && result.message) {
                this.$message.error(result.message)
              }
            })
      })
    },

    /**
     * 处理删除
     * @param {Object} knowledge - 知识库对象
     */
    handleDelete(knowledge) {
      this.$confirm(`确认删除知识库 "${knowledge.name}"?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('knowledge/deleteKnowledge', knowledge.id)
            .then(result => {
              if (result && result.success) {
                this.$message.success('删除成功')
              } else if (result && result.message) {
                this.$message.error(result.message)
              }
            })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    /**
     * 显示标签输入框
     */
    showTagInput() {
      this.inputTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    /**
     * 处理标签关闭
     * @param {Object} tag - 标签对象
     */
    handleTagClose(tag) {
      this.currentKnowledge.tags = this.currentKnowledge.tags.filter(t => t.id !== tag.id)
    },

    /**
     * 处理标签确认
     */
    handleTagConfirm() {
      if (this.inputTagValue) {
        // 生成临时ID（实际应该由后端生成）
        const tempId = Date.now()
        this.currentKnowledge.tags.push({
          id: tempId,
          name: this.inputTagValue,
          knowledge_id: this.currentKnowledge.id
        })
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },

    /**
     * 关闭对话框
     */
    closeDialog() {
      // 清理Excalidraw实例
      if (this.excalidrawInstance) {
        this.excalidrawInstance = null
      }
      this.excalidrawData = null
      this.dialogVisible = false
    },

    /**
     * 打开Excalidraw画板对话框
     */
    openExcalidrawDialog(knowledge) {
      this.currentExcalidrawKnowledge = knowledge
      this.excalidrawDialogVisible = true

      // 在下一个事件循环中初始化Excalidraw
      this.$nextTick(() => {
        this.initExcalidrawInDialog()
      })
    },

    /**
     * 在对话框中初始化Excalidraw
     */
    initExcalidrawInDialog() {
      // 确保容器存在
      if (!this.$refs.excalidrawDialogContainer) return

      // 清空容器
      this.$refs.excalidrawDialogContainer.innerHTML = ''

      // 创建Excalidraw实例
      const excalidrawDiv = document.createElement('div')
      excalidrawDiv.style.width = '100%'
      excalidrawDiv.style.height = '600px'
      this.$refs.excalidrawDialogContainer.appendChild(excalidrawDiv)

      // 初始化Excalidraw
      this.excalidrawInstance = Excalidraw.createRoot(excalidrawDiv, {
        viewModeEnabled: false,
        zenModeEnabled: false,
        gridModeEnabled: true
      })

      // 加载数据
      if (this.currentExcalidrawKnowledge && this.currentExcalidrawKnowledge.id) {
        this.loadExcalidrawData(this.currentExcalidrawKnowledge.id)
      }

      // 监听变化
      this.excalidrawInstance.onChange = (elements, appState) => {
        this.excalidrawData = {elements, appState}
      }
    },

    /**
     * 从对话框保存Excalidraw数据
     */
    saveExcalidrawFromDialog() {
      if (!this.currentExcalidrawKnowledge || !this.currentExcalidrawKnowledge.id) {
        this.$message.warning('无法保存画板数据')
        return
      }

      const excalidrawData = this.getExcalidrawData()
      if (!excalidrawData) {
        this.$message.warning('画板数据为空，无需保存')
        return
      }

      this.$store.dispatch('knowledge/saveKnowledgeExcalidraw', {
        id: this.currentExcalidrawKnowledge.id,
        excalidraw: excalidrawData
      }).then(result => {
        if (result && result.success) {
          this.$message.success('画板数据保存成功')
          // 刷新知识库列表
          this.fetchKnowledgeList()
        } else if (result && result.message) {
          this.$message.error(result.message)
        }
      })
    },

    /**
     * 关闭Excalidraw对话框
     */
    closeExcalidrawDialog() {
      // 清理Excalidraw实例
      if (this.excalidrawInstance) {
        this.excalidrawInstance = null
      }
      this.excalidrawData = null
      this.currentExcalidrawKnowledge = null
      this.excalidrawDialogVisible = false
    },

    /**
     * 打开附件管理对话框
     */
    openAttachmentsDialog(knowledge) {
      this.currentAttachmentKnowledgeId = knowledge.id
      this.attachmentsDialogVisible = true
      this.fetchAttachments(knowledge.id)
    },

    /**
     * 获取附件列表
     */
    fetchAttachments(knowledgeId) {
      if (!knowledgeId) return

      this.attachmentsLoading = true
      this.$store.dispatch('knowledge/getExcalidrawAttachments', knowledgeId)
          .then(result => {
            this.attachmentsLoading = false
            if (result && result.success && result.data) {
              this.attachmentsList = result.data
            } else {
              this.attachmentsList = []
              if (result && result.message) {
                this.$message.warning(result.message)
              }
            }
          })
          .catch(() => {
            this.attachmentsLoading = false
            this.attachmentsList = []
          })
    },

    /**
     * 上传前验证
     */
    beforeAttachmentUpload(file) {
      // 可以在这里添加文件类型、大小等验证
      return true
    },

    /**
     * 上传附件
     */
    uploadAttachment(options) {
      const {file} = options

      if (!this.currentAttachmentKnowledgeId) {
        this.$message.error('无法上传附件，知识库ID不存在')
        return
      }

      this.$store.dispatch('knowledge/uploadExcalidrawAttachment', {
        knowledgeId: this.currentAttachmentKnowledgeId,
        file
      }).then(result => {
        if (result && result.success) {
          this.$message.success('附件上传成功')
          // 刷新附件列表
          this.fetchAttachments(this.currentAttachmentKnowledgeId)
        } else if (result && result.message) {
          this.$message.error(result.message)
        }
      })
    },

    /**
     * 查看附件
     */
    viewAttachment(attachment) {
      // 在新窗口中打开附件
      if (attachment && attachment.excalidraw_json_url) {
        window.open(attachment.excalidraw_json_url, '_blank')
      }
    },

    /**
     * 删除附件
     */
    deleteAttachment(attachment) {
      this.$confirm(`确认删除此附件?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('knowledge/deleteExcalidrawAttachment', attachment.id)
            .then(result => {
              if (result && result.success) {
                this.$message.success('删除成功')
                // 刷新附件列表
                this.fetchAttachments(this.currentAttachmentKnowledgeId)
              } else if (result && result.message) {
                this.$message.error(result.message)
              }
            })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    /**
     * 关闭附件对话框
     */
    closeAttachmentsDialog() {
      this.attachmentsList = []
      this.currentAttachmentKnowledgeId = null
      this.attachmentsDialogVisible = false
    }
  }
}
</script>

<style scoped>
.knowledge-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.content-preview {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.excalidraw-container {
  width: 100%;
  height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.excalidraw-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

.no-excalidraw-data {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.excalidraw-fullscreen {
  height: 600px;
}

.attachments-container {
  padding: 10px 0;
}

.upload-area {
  margin-bottom: 20px;
}

.attachment-preview {
  width: 80px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
}

.no-preview {
  color: #909399;
  font-size: 12px;
}
</style>
